package com.xue.springcloud.controller;

import com.xue.springcloud.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 通过RestTemplate请求提供者端的接口
 * */
@RestController
@RequestMapping("consumer")
public class DeptConsumerController {

    //消费端不应该有service层
    //通过RestTemplate (Spring3.0开始支持的一个HTTP请求工具,简单地restful服务模板) 去请求

    //    不做负载均衡时，可写死地址接口前缀
//    private static String URL_PREFIX = "http://localhost:8001/";

    //    通过Ribbon做负载均衡，应该是是一个变量，通过服务名来访问()
    /**
     * Ribbon的默认算法是轮循
     * */
    private static String URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT/";

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("dept/get/{id}")
    public Dept get(@PathVariable("id") Long id){
        return restTemplate.getForObject(URL_PREFIX+"dept/get/"+id,Dept.class);
    }

    @RequestMapping("dept/list")
    public List<Dept> list(){
        return restTemplate.getForObject(URL_PREFIX+"dept/list",List.class);
    }

    @RequestMapping("dept/add")
    public Boolean add(@RequestBody Dept dept){
        return restTemplate.postForObject(URL_PREFIX+"dept/add",dept,Boolean.class);
    }
}
